<template>
  <a-card class="page-main page-main-admin" :bordered="false" v-title data-title="项目奖励申请规则">

    <div class="container">
      <div class="hte-head-content">
        <span class="bold-font">项目奖励申请规则</span>

      </div>
      <div class="content-admin">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="queryList">
            <a-row :gutter="24">
              <a-col :span="8" class="hte-col-nowrap">
                <a-form-item label="项目类型" prop="projectSubType">
                  <a-select v-model="queryParam.projectSubType" placeholder="请选择项目类型" :options="projectSubTypeOptions"/>
                </a-form-item>
              </a-col>
              <a-button type="primary" icon="search" @click="queryList">查询</a-button>
              <a-button type="default" style="margin-left:16px" @click="searchReset">重置</a-button>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="handleAdd" v-has="'masterData:projectRewardRules:edit'" type="primary" icon="plus">新增
          </a-button>
          <a-button v-has="'masterData:projectRewardRules:edit'" type="primary" icon="import"
                    @click="importExcelDataBtn">导入
          </a-button>
          <a-button v-has="'masterData:projectRewardRules:edit'" icon="check-circle"
                    @click="active">生效
          </a-button>
          <a-button v-has="'masterData:projectRewardRules:edit'" icon="close-circle"
                    @click="cancelActive">撤销
          </a-button>
          <a-button type="default" @click="batchDelRules" v-has="'masterData:projectRewardRules:del'">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
            selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>

          <a-table
            ref="table"
            size="middle"
            :scroll="{x:true}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="false"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            :customHeaderRow="customHeaderRow"
            class="j-table-force-nowrap"
            @change="handleTableChange">

            <span slot="needRerunTest" slot-scope="text, record">
              {{!!record.needRerunTest?'是':'否'}}
            </span>
            <span slot="isActive" slot-scope="text, record">
              {{record.isActive?'生效中':'未生效'}}
            </span>
            <span slot="action" slot-scope="text, record">
              <span v-show="!record.isActive"><a @click="handleEdit(record)" v-has="'masterData:projectRewardRules:edit'">编辑</a></span>
            </span>
          </a-table>
        </div>
      </div>
    </div>

    <project-reward-rules-modal ref="modalForm" @ok="reloadTable" @checkRepeat="checkRepeat"
                                :projectSubTypeOptions="projectSubTypeOptions"></project-reward-rules-modal>
    <excel-paste :columnsExcel="columnsExcel" :exportXlsTemplateUrl="exportXlsTemplateUrl" :excelVisible="excelVisible"
                 :excelConfirmLoading="excelConfirmLoading" @handleOkExcel="handleOkExcel"
                 @handleCancelExcel="handleCancelExcel"></excel-paste>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import {mixinDevice} from '@/utils/mixin'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import ProjectRewardRulesModal from './modules/ProjectRewardRulesModal'
  import ExcelPaste from '@/components/excelPaste/ExcelPaste'
  import {httpAction, getAction, postAction,deleteAction} from '@/api/manage'

  export default {
    name: 'ProjectRewardRules',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      ProjectRewardRulesModal, ExcelPaste
    },
    data() {
      return {
        description: '项目奖励申请规则',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '项目类型',
            align: "center",
            dataIndex: 'projectSubTypeName'
          },
          {
            title: '时间节点',
            align: "center",
            dataIndex: 'timeNodeName'
          },
          {
            title: '奖励比例区间开始(%)',
            align: "center",
            dataIndex: 'presentStart'
          },
          {
            title: '奖励比例区间结束(%)',
            align: "center",
            dataIndex: 'presentEnd'
          },
          {
            title: '节点累计提取比例上限(%)',
            align: "center",
            dataIndex: 'cumulativePresentLimit'
          },
          {
            title: '成果目标权重',
            align: "center",
            dataIndex: 'targetWeight'
          },
          {
            title: '进度目标权重',
            align: "center",
            dataIndex: 'progressWeight'
          },
          {
            title: '经济目标达成率占比',
            align: "center",
            dataIndex: 'economyTargetWeight'
          },
          {
            title: '是否需要重跑价值表',
            align: "center",
            dataIndex: 'needRerunTest',
            scopedSlots: {customRender: 'needRerunTest'}
          },
          {
            title: '生效状态',
            align: "center",
            dataIndex: 'isActive',
            scopedSlots: {customRender: 'isActive'}
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 100,
            scopedSlots: {customRender: 'action'}
          }
        ],
        url: {
          list: "/projectRewardRules/list",
          getCodeInfoList: "/manage/codeInfo/queryByType",
          deleteBatch: "/projectRewardRules/deleteBatch",
          importExcelUrl: "/projectRewardRules/importExcel",
          addBatch: '/projectRewardRules/addBatch',
          updateActive: '/projectRewardRules/updateActive',
        },
        projectSubTypeList: [],
        projectSubTypeOptions: [],
        dictOptions: {},
        superFieldList: [],
        columnsExcel: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            },
            isImportExcelColumns: false
          },
          {
            title: '项目类型(必填)',
            align: "center",
            dataIndex: 'projectSubType'
          },
          {
            title: '时间节点编号(必填)',
            align: "center",
            dataIndex: 'timeNodeCode'
          },
          {
            title: '奖励比例区间开始(必填)',
            align: "center",
            dataIndex: 'presentStart'
          },
          {
            title: '奖励比例区间结束(必填)',
            align: "center",
            dataIndex: 'presentEnd'
          },
          {
            title: '节点累计提取比例上限',
            align: "center",
            dataIndex: 'cumulativePresentLimit'
          },
          {
            title: '成果目标权重',
            align: "center",
            dataIndex: 'targetWeight'
          },
          {
            title: '进度目标权重',
            align: "center",
            dataIndex: 'progressWeight'
          },
          {
            title: '是否需要重跑价值表',
            align: "center",
            dataIndex: 'needRerunTest'
          },
        ],
        excelVisible: false,
        excelConfirmLoading: false,
        excelDataSource: [],
        exportXlsTemplateUrl: 'templates/excel/ProjectRewardRulesTemplate.xlsx'
      }
    },
    created() {
      this.getProjectSubTypeList();
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      getProjectSubTypeList() {
        const that = this;
        getAction(this.url.getCodeInfoList, {type: "项目需求类型"}).then(res => {
          this.projectSubTypeList = res.result || [];
          getAction(this.url.getCodeInfoList, {type: "项目子类"}).then(res => {
            this.projectSubTypeList = this.projectSubTypeList.concat(res.result || []);
            if (this.projectSubTypeList.length > 0) {
              this.projectSubTypeList.forEach(function (item) {
                that.projectSubTypeOptions.push({
                  value: item.code.trim(),
                  label: item.name.trim() + '(' + item.code.trim() + ')'
                });
              })
            }
          })
        })
      },
      queryList() {
        const that = this;
        getAction(this.url.list, {projectSubType: this.queryParam.projectSubType || ''}).then(res => {
          debugger
          if (res.code === 200) {
            this.dataSource = res.result || [];
          } else {
            this.$message.warning('查询异常:' + res.message);
          }
        }).catch(res => {
          this.excelConfirmLoading = false;
          this.$message.warning('查询异常:' + res.message);

        })
      },
      reloadTable() {
        this.queryList();
        this.onClearSelected();
      },
      checkRepeat(record) {
        let checkData;
        if(record.id){
          checkData=this.dataSource.filter(d=>{
            return d.id!==record.id&&
              d.projectSubType===record.projectSubType&&
              d.timeNodeCode===record.timeNodeCode
          })
        }else{
          checkData=this.dataSource.filter(d=>{
            return d.projectSubType===record.projectSubType&&
              d.timeNodeCode===record.timeNodeCode
          })
        }
        if(checkData&&checkData.length>0){
          this.$message.warning('项目类型【'+record.projectSubType+'】时间节点【'+checkData[0].timeNodeName+'】规则重复，请检查');
          this.$set(record,'isRepeat',true);
        }else{
          this.$set(record,'isRepeat',false);
        }
      },
      handleOkExcel: function (data) {
        let allData=JSON.parse(JSON.stringify(this.dataSource));
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          if (item.projectSubType == '' || item.timeNodeCode == '' || item.presentStart == ''
            || item.presentEnd == '' || item.needRerunTest == ''
            || item.targetWeight == '' || item.progressWeight == '') {
            this.$message.warning('第 ' + (i + 1) + ' 行，请先把必填项填写完整');
            return;
          }
          let checkData=allData.filter(d=>{
            return d.projectSubType===item.projectSubType&&
              d.timeNodeCode===item.timeNodeCode
          });
          if(checkData&&checkData.length>0){
            this.$message.warning('第 '+(i+1)+' 行，项目类型【'+item.projectSubType+'】时间节点【'+checkData[0].timeNodeName+'】规则重复，请检查');
            return;
          }
          let targetWeight=parseFloat(item.targetWeight);
          let progressWeight=parseFloat(item.progressWeight);
          if(isNaN(targetWeight)||isNaN(progressWeight)||parseFloat((targetWeight+progressWeight).toFixed(2))!==1){
            this.$message.warning('第 '+(i+1)+' 行，权重值不正确或者相加不为1');
            return;
          }

          item.needRerunTest = item.needRerunTest =='是'?'true':'false';
          allData.push(item);
        }

        this.excelDataSource = data;
        //数据验证
        this.excelConfirmLoading = true;
        postAction(this.url.addBatch, data).then(res => {
          this.excelConfirmLoading = false;
          if (res.code === 200) {

            this.excelVisible = false;
            this.$message.success("导入成功");
            this.queryList();
          } else {
            this.$message.warning('操作异常:' + res.message);
          }
        }).catch(res => {
          this.excelConfirmLoading = false;
          this.$message.warning('操作异常:' + res.message);

        })
      },
      importExcelDataBtn: function () {
        this.excelVisible = true;
      },
      handleCancelExcel: function () {
        this.excelVisible = false;

      },
      active(){
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        }
        let checkData=this.selectionRows.filter(r=>{return r.isActive});
        if(checkData&&checkData.length>0){
          this.$message.warning('选择的记录都已生效');
          return;
        }
        this.updateActive(true)
      },
      cancelActive(){
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        }
        let checkData=this.selectionRows.filter(r=>{return !r.isActive});
        if(checkData&&checkData.length>0){
          this.$message.warning('选择已生效的记录');
          return;
        }
        this.updateActive(false)
      },
      updateActive(isActive){
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "提示",
          content: "确定"+(isActive?"生效":"撤销")+"选中数据?",
          onOk: function() {
            that.loading = true;
            getAction(that.url.updateActive, { ids: ids,isActive:isActive }).then((res) => {
              if (res.success) {
                //重新计算分页问题
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      },
      batchDelRules: function() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        }
        let checkData=this.selectionRows.filter(r=>{return r.isActive});
        if(checkData&&checkData.length>0){
          this.$message.warning('生效中的记录不能删除，请先撤销生效！');
          return;
        }

        let ids = this.selectedRowKeys.join(",");
        const that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function() {
            that.loading = true;
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                //重新计算分页问题
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      },
      customHeaderRow(column, index) {
        return {
          on: {
            click: () => {
              this.$message.info('附加字段2(对于时间表固定节点的报工人，填oneAccount),附加字段3(现在用于时间表固定节点的工作完成内容)');
            },
          }
        }
      }
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';
  @import '~@assets/less/hte-main.less';

  .table-operator {
    margin-top: 10px;
  }
</style>